import { debounce } from './tools';
const showErrorMessage = debounce((errMessage) => {
    console.error(errMessage);
}, 500);
export const request = (url, config, options = {}) => {
    config.headers = config.headers || {};
    config.headers['Token'] = localStorage.getItem('Token');
    return new Promise((resolve, reject) => {
        fetch(url, config)
            .then((res) => {
                if (res.ok) {
                    res.text().then((resText) => {
                        const resp = JSON.parse(resText);
                        const success = resp.success || resp.isSuccess;
                        const errMessage = resp.message || resp.resultMsg;
                        if (success) {
                            resolve(options.rawResponse ? resp : resp.data);
                        } else {
                            if (resp.code === 401) {
                                // 无权访问
                                window.location = '/login';
                            } else {
                                showErrorMessage(errMessage);
                                reject(errMessage);
                            }
                        }
                    });
                } else {
                    // 服务器异常
                    if (!options.noErrorMessage) {
                        showErrorMessage('服务器异常');
                    }
                    reject('服务器异常');
                }
            })
            .then((resJson) => {
                return resJson;
            })
            .catch((error) => {
                if (!options.noErrorMessage) {
                    showErrorMessage('请求失败');
                }
                reject(error);
            });
    });
};

export const get = (url, params, options = {}) => {
    let paramsString = '';
    if (params && typeof params === 'object' && Object.keys(params).length > 0) {
        paramsString =
            '?' +
            Object.keys(params)
                .filter(key => params[key] !== undefined && params[key] !== null)
                .map((key) => `${key}=${params[key]}`)
                .join('&');
    }
    return request(`${url}${paramsString}`, { method: 'GET' }, options);
};

export const post = (url, data, options = {}) => {
    return request(
        url,
        {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify(data),
        },
        options
    );
};

export const put = (url, data, options = {}) => {
    return request(
        url,
        {
            method: 'PUT',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify(data),
        },
        options
    );
};

export const del = (url, config, options = {}) => {
    return request(
        url,
        {
            method: 'DELETE',
        },
        options
    );
};
